package miroshnichenko.gallery.service;

import miroshnichenko.gallery.dao.ImageItemDao;
import miroshnichenko.gallery.domain.ImageItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;

@Service
public class ThumbnailServiceImpl implements ThumbnailService {

    private static final int THUMBNAIL_HEIGHT = 200;
    private static final int THUMBNAIL_WIDTH = 200;

    @Autowired
    private ImageItemDao imageItemDao;

    public BufferedImage getThumbnail(int imageItemId) throws IOException {
        ImageItem image = imageItemDao.retrieveImage(imageItemId);

        byte[] imageContent = image.getFileContent();
        BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(imageContent));

        return createThumb(bufferedImage);
    }

    private BufferedImage createThumb(BufferedImage sourceImage) throws IOException {
        int width = sourceImage.getWidth();
        int height = sourceImage.getHeight();

        if(width>height){
            float extraSize = height - THUMBNAIL_HEIGHT;
            float percentHeight = (extraSize / height) * 100;
            float percentWidth = width - ((width / 100) * percentHeight);

            BufferedImage img = new BufferedImage((int)percentWidth, THUMBNAIL_HEIGHT, BufferedImage.TYPE_INT_RGB);
            Image scaledImage = sourceImage.getScaledInstance((int)percentWidth, THUMBNAIL_HEIGHT, Image.SCALE_AREA_AVERAGING);
            img.createGraphics().drawImage(scaledImage, 0, 0, null);

            return img.getSubimage((int)((percentWidth - THUMBNAIL_HEIGHT) / 2), 0, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
        }else{
            float extraSize = width - THUMBNAIL_WIDTH;
            float percentWidth = (extraSize / width) * 100;
            float  percentHeight = height - ((height / 100) * percentWidth);

            BufferedImage img = new BufferedImage(THUMBNAIL_WIDTH, (int)percentHeight, BufferedImage.TYPE_INT_RGB);
            Image scaledImage = sourceImage.getScaledInstance(THUMBNAIL_WIDTH, (int)percentHeight, Image.SCALE_AREA_AVERAGING);
            img.createGraphics().drawImage(scaledImage, 0, 0, null);

            return img.getSubimage(0, (int)((percentHeight - THUMBNAIL_WIDTH) / 2), THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
        }
    }
}
